package org.linlinjava.litemall.core.filter;


import org.apache.commons.lang3.StringUtils;
import org.linlinjava.litemall.core.util.ResponseUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@WebFilter(urlPatterns = "/*")
public class XssFilter implements Filter {
	private String filterChar;
	private String replaceChar;
	private String splitChar;
	FilterConfig filterConfig = null;
	private List<String> sqlKeyWords = Arrays.asList("where","1=1","insert","group","count");
	static Logger log = LoggerFactory.getLogger(XssFilter.class);
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterChar=filterConfig.getInitParameter("FilterChar");
		this.replaceChar=filterConfig.getInitParameter("ReplaceChar");
		this.splitChar=filterConfig.getInitParameter("SplitChar");
		this.filterConfig = filterConfig;
	}


	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {

		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
//

		HttpServletRequest xssRequest = new XssHttpServletRequestWrapper(req);

		String requestStr = getRequestString(req);
		log.info("requestStr:{}",requestStr);
		if (isValidRequestUri(requestStr)
				||isValidRequestUri(req.getRequestURL().toString())) {
			log.info("======访问地址发现非法字符，已拦截======其非法地址为：" + requestStr);
			ResponseUtils.renderText(res, "Illegal Request URI!");
			return;
		}

		chain.doFilter(xssRequest, response);
	}

	/**
	 * 是否sql关键字
	 * @param requestAddress
	 * @return
	 */
	private boolean isSqlKeyWord(String requestAddress){
		for (String key : sqlKeyWords) {
			if(requestAddress.contains(key)){
				return true;
			}
		}
		return false;
	}
	private String getRequestString(HttpServletRequest req) {
		String requestPath = req.getServletPath().toString();
		String queryString = req.getQueryString();
		if (queryString != null){
			return requestPath + "?" + queryString;
		}
		else{
			return requestPath;
		}

	}

	public boolean isValidRequestUri(String a) {
		if (StringUtils.isNotEmpty(a)) {
			if (a.contains("%22") || a.contains("%3E") || a.contains("%3e")
					|| a.contains("%3C") || a.contains("%3c")
					|| a.contains("<") || a.contains(">") || a.contains("\"")
					|| a.contains("'")|| a.contains(" and ")
					|| a.contains(" or ") || a.contains("1=1") || a.contains("(") || a.contains(")")) {
				return true;
			}
		}
		return false;
	}

	private boolean isExcludeUrl(HttpServletRequest request) {
		String uri = request.getRequestURI();
		String ctx = request.getContextPath();
		if (StringUtils.isNotBlank(ctx)) {
			uri = uri.substring(ctx.length());
		}
		return false;
	}

	@Override
	public void destroy() {
	}

}
